/* eslint-disable react/jsx-key */
import React, { useState, useRef, useEffect } from 'react';
import ReactDOM from 'react-dom';
import { Image, Switch, Tooltip, Modal, message, Popconfirm } from 'antd';
import AutoTable from '@/components/AutoTable';
import InitForm from '@/components/InitForm';
import { deletepaymentorder, companydetail, company, otherbusinesstake } from '@/services/business';
import { search } from '@/services/basic';
import { customer } from '@/services/customer';
import { area, classify, user, payment_cycle, payment } from '@/services/basic';
import { connect } from 'umi';
import { PlusOutlined, DownloadOutlined } from '@ant-design/icons';
import ProDescriptions from '@ant-design/pro-descriptions';
import moment from 'moment';
import { getFetch } from '@/utils/doFetch';
import CompanyName from '@/components/CompanyName';


// type 类型有 table treeselect upload inputnumber datepicker daterange radio select textarea autoinput editor password input

let valueEnum = {
    cache: {
      text: '暂存',
    },
    stalled: {
      text: '未开始',
    },
    dispatching: {
      text: '会计调度中',
    },
    dispatch_refuse: {
      text: '会计调度拒绝',
    },
    accounting: {
      text: '记账会计审核中',
    },
    account_refuse: {
      text: '记账会计拒绝',
    },
    account_cache: {
      text: '记账会计暂存',
    },
    completed: {
      text: '已完成',
    },
  },
  valueEnums = {
    cache: {
      text: '待激活',
      status: 'error',
    },
    cashiering: {
      text: '出纳审核中',
    },
    cashier_refuse: {
      text: '出纳拒绝',
    },
    accounting: {
      text: '会计审核中',
    },
    account_refuse: {
      text: '会计拒绝',
    },
    completed: {
      text: '已完成',
    },
  };

function Receipt(props) {
  let defaultFields = {
    company_id: {
      value: null,
      type: 'select',
      title: '公司',
      name: ['company_id'],
      required: true,
      linked: true,
      options: {
        database: () => getFetch({ url: '/wbn-api/company/all_company_list', params: {} }),
        params: {},
      },
    },
    service_type: {
      value: 'account',
      type: 'select',
      title: '服务类型',
      name: ['service_type'],
      required: true,
      linked: true,
      options: [
        {
          label: '代账',
          value: 'account',
        },
        {
          label: '其他业务',
          value: 'other',
          disabled: true,
        },
      ],
    },
    service_id: {
      value: 'account',
      type: 'select',
      title: '服务名称',
      name: ['service_id'],
      required: true,
      options: {
        database: otherbusinesstake,
        params: {},
      },
      belinked: {
        hides: [
          {
            name: 'service_type',
            equalvalue: ['account'],
            required: true,
          },
        ],
      },
    },
    receivable: {
      value: null,
      type: 'inputnumber',
      title: '应收款',
      name: ['receivable'],
      required: true,
    },
    actual_receive: {
      value: null,
      type: 'inputnumber',
      title: '实际收款',
      name: ['actual_receive'],
      required: true,
    },
    service: {
      value: null,
      type: 'daterange',
      title: '服务区间',
      name: ['service'],
      required: true,
      belinked: {
        hides: [
          {
            name: 'service_type',
            unequalvalue: ['account'],
            required: true,
          },
        ],
      },
    },
    payment_cycle_id: {
      value: null,
      type: 'select',
      title: '收款周期',
      name: ['payment_cycle_id'],
      options: {
        database: payment_cycle,
        params: {
          is_all: 1,
        },
      },
      required: true,
      belinked: {
        hides: [
          {
            name: 'service_type',
            unequalvalue: ['account'],
            required: true,
          },
        ],
      },
    },
    payment_id: {
      value: null,
      type: 'select',
      title: '收款方式',
      name: ['payment_id'],
      options: {
        database: payment,
        params: {
          is_all: 1,
        },
      },
      required: true,
    },

    payment_type: {
      value: null,
      type: 'select',
      title: '收款类型',
      name: ['payment_type'],
      options: [
        {
          label: '全款',
          value: 'full',
        },
        {
          label: '定金',
          value: 'deposit',
        },
        {
          label: '尾款',
          value: 'balance',
        },
      ],
      required: true,
    },
    payment_time: {
      value: null,
      type: 'datepicker',
      title: '收款日期',
      name: ['payment_time'],
      required: true,
      disabledDate: (current) => {
        return current && current > moment().endOf('day');
      },
      options: {
        database: customer,
        params: { is_all: 1 },
      },
    },
    remark: {
      value: null,
      type: 'textarea',
      title: '备注',
      name: ['remark'],
      required: false,
      col: { span: 24 },
    },
    cashier_user_id: {
      value: null,
      type: 'select',
      title: '选择出纳',
      name: ['cashier_user_id'],
      required: true,
      belinked: {
        options: {
          database: search,
          params: {
            is_all: 1,
            role_id: 2, //出纳
            company_id: 'linked',
          },
        },
      },
      col: { span: 24 },
    },
  };
  const [vs, cvs] = useState(false), //表单显/隐
    [vis, cvis] = useState(false),
    [fields, cf] = useState(defaultFields),
    [iftype, ciftype] = useState({}),
    {
      location: { query },
    } = props;

  let actionRef = useRef(),
    ChildRef = null,
    formRef = useRef();

  function reload() {
    actionRef?.current?.reload();
    ChildRef?.onRefresh();
  }
  const columns = [
    {
      title: '本期收费单号',
      dataIndex: 'settle_id',
      key: 'settle_id',
      width: 100,
      copyable: true,
      search: false,
      render: (_, row) => (
        <span>{row.settle_id ? (Array(5).join(0) + row.settle_id).slice(-5) : '-'}</span>
      ),
    },
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'company_name',
      key: 'company_name',
      copyable: true,
      render: (_, row) => (
        <CompanyName
          row={{ ...row, name: row?.company_name ?? row?.name, id: row?.company_id ?? row?.id }}
          reload={reload}
        />
      ),
    },
    {
      title: '业务类型',
      dataIndex: 'service_type_name',
      key: 'service_type_name',
      search: false,
    },

    {
      title: '应收款',
      dataIndex: 'receivable',
      key: 'receivable',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '服务开始时间',
      dataIndex: 'service_start_time',
      key: 'service_start_time',
      width: 100,
      search: false,
    },
    {
      title: '服务结束时间',
      dataIndex: 'service_end_time',
      key: 'service_end_time',
      width: 100,
      search: false,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '支付周期',
      dataIndex: 'payment_cycle_name',
      key: 'payment_cycle_name',
      search: false,
    },
    {
      title: '周期月数',
      dataIndex: 'cycle_num',
      key: 'cycle_num',
      search: false,
    },
    {
      title: '支付类型',
      dataIndex: 'payment_type',
      key: 'payment_type',
      valueType: 'select',
      options: [
        {
          id: 'full',
          name: '全款',
        },
        {
          id: 'deposit',
          name: '定金',
        },
        {
          id: 'balance',
          name: '尾款',
        },
      ],
      valueEnum: {
        full: {
          text: '全款',
        },
        deposit: {
          text: '定金',
        },
        balance: {
          text: '尾款',
        },
      },
    },
    {
      title: '收款日期',
      dataIndex: 'payment_time',
      key: 'payment_time',
      width: 100,
    },
    {
      title: '实际收款',
      dataIndex: 'actual_receive',
      key: 'actual_receive',
    },
    {
      title: '收款方式',
      dataIndex: 'payment_name',
      key: 'payment_id',
      valueType: 'select',
      options: {
        database: payment,
        params: {
          is_all: 1,
        },
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      search: false,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueType: 'select',
      options: [
        {
          value: 'cashier_refuse',
          label: '出纳拒绝',
        },
        {
          value: 'cache',
          label: '待激活',
        },
      ],
      width: 100,
      valueEnum: valueEnums,
      render: (dom, row) => (
        <div
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
          onClick={() => {
            if (row?.status?.indexOf('refuse') != -1) {
              Modal.info({
                title: '拒绝原因',
                content: row.cashier_refuse_message,
                maskClosable: true,
              });
            }
          }}
        >
          {valueEnums[row?.status]?.text}
        </div>
      ),
    },
    {
      title: '操作',
      valueType: 'option',
      width: 160,
      render: (text, record, _, action) => [
        <a
          onClick={() => {
            ciftype({
              ...iftype,
              val: 'see',
              title: '查看详情',
              curitem: record,
            });
            cvs(true);
          }}
        >
          详情
        </a>,
        <a
          disabled={record.status != 'cashier_refuse' && record.status != 'cache'}
          style={{
            color:
              record.status != 'cashier_refuse' && record.status != 'cache' ? '#999' : '#1890ff',
          }}
          onClick={() => {
            if (record.status != 'cashier_refuse' && record.status != 'cache') {
              return;
            }
            cvs(true);
            cf((fields) => {
              for (let i in fields) {
                fields[i].value = record[i];
                if (i == 'service') {
                  fields[i].value = record.service_start_time
                    ? [record.service_start_time, record.service_end_time]
                    : null;
                }
              }
              return { ...fields };
            });
            ciftype({
              val: 'edit',
              title: '编辑收款单',
              id: record.id,
              curitem: record,
              type: record.status,
            });
          }}
        >
          编辑
        </a>,
        <Popconfirm
          placement="bottom"
          title={'确认删除该收款单？'}
          onConfirm={() => {
            deletepaymentorder(record.id).then((res) => {
              if (res.code == 0) {
                message.success('操作成功');
                reload();
              }
            });
          }}
          okText="删除"
          disabled={record.status != 'cashier_refuse' && record.status != 'cache'}
          cancelText="取消"
        >
          <a
            disabled={record.status != 'cashier_refuse' && record.status != 'cache'}
            style={{
              color:
                record.status != 'cashier_refuse' && record.status != 'cache' ? '#999' : '#f50',
            }}
          >
            删除
          </a>
        </Popconfirm>,
      ],
    },
  ];

  const columnes = [
    {
      title: '公司名称',
      width: 260,
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '公司法人',
      dataIndex: 'legal_person',
      key: 'legal_person',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司地址',
      dataIndex: 'address',
      key: 'address',
      search: false,
      hideInTable: true,
    },
    {
      title: '统一社会信用代码',
      dataIndex: 'enterprise_credit_code',
      key: 'enterprise_credit_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '公司营业执照',
      dataIndex: 'origin_url',
      key: 'origin_url',
      render: (_, row) => {
        return <Image width={32} height={32} style={{ padding: 2 }} src={row.origin_url}></Image>;
      },
      hideInTable: true,
      search: false,

    },
    {
      title: '联系人',
      dataIndex: 'customer_name',
      key: 'customer_name',
      ellipsis: true,
    },
    {
      title: '联系人手机号',
      width: 120,
      dataIndex: 'customer_phone',
      key: 'customer_phone',
      render: (_, row) => (
        <Tooltip title={row.customer_phone}>
          <a href={`tel:${row.customer_phone}`} className="oneline">
            {row.customer_phone}
          </a>
        </Tooltip>
      ),
    },
    {
      title: '区域名称',
      dataIndex: 'area_name',
      key: 'area_name',
      search: false,
    },
    {
      title: '区域编码',
      dataIndex: 'area_code',
      key: 'area_code',
      search: false,
      hideInTable: true,
    },
    {
      title: '接单人',
      dataIndex: 'user_name',
      key: 'user_name',
      search: false,
    },
    {
      title: '促单人',
      dataIndex: 'promoter_user_name',
      key: 'promoter_user_name',
      search: false,
    },
    {
      title: '公司类型',
      dataIndex: 'classify_name',
      key: 'classify_name',
      search: false,
    },
    {
      title: '月收费',
      dataIndex: 'unit_price',
      key: 'unit_price',
      search: false,
    },
    {
      title: '活动',
      dataIndex: 'activity_content',
      key: 'activity_content',
      search: false,
      hideInTable: true,
    },
    {
      title: '续单',
      dataIndex: 'is_create_order',
      key: 'is_create_order',
      search: false,
      render: (_, row) => <span>{row.is_create_order ? '是' : '否'}</span>,
    },
    {
      title: '会计流程',
      dataIndex: 'is_accountant',
      key: 'is_accountant',
      search: false,
      render: (_, row) => <span>{row.is_accountant ? '是' : '否'}</span>,
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: valueEnum,
      width: 120,
      render: (dom, row) => (
        <div
          style={{
            color: row?.status?.indexOf('refuse') != -1 ? 'red' : 'auto',
            cursor: 'pointer',
          }}
        >
          {valueEnum[row?.status]?.text}
        </div>
      ),
    },
    {
      title: '合同协议',
      dataIndex: 'contracts',
      key: 'contracts',
      search: false,
      render: (_, row) => {
        if (!row.contracts) {
          return (
            <Image
              width={32}
              height={32}
              style={{ padding: 2 }}
              src={require('@/assets/default.png')}
            ></Image>
          );
        } else {
          return row.contracts.map((it) => {
            return (
              <Image width={32} height={32} src={it.origin_url} style={{ padding: 2 }}></Image>
            );
          });
        }
      },
      hideInTable: true,
    },
  ];

  let extrarender = [
    <div
      className="action"
      title="新增"
      style={{ marginRight: 12 }}
      onClick={() => {
        cvs(true);
        cf((fields) => {
          for (let i in fields) {
            fields[i].value = i == 'service_type' ? 'account' : null;
          }
          return { ...fields };
        });
        ciftype({
          val: 'add',
          title: '新增收款单',
        });
      }}
    >
      <PlusOutlined />
    </div>,
    <div
      className="action"
      title="导出"
      style={{ background: '#ff4800' }}
      onClick={() => {
        const hide = message.loading('正在导出..', 0);
        let julu = formRef?.current?.getFieldValue() ?? {};
        getFetch({ url: '/wbn-api/payment_order/batch_import', params: { ...julu, type: 0 } }).then(
          (res) => {
            if (res?.data) {
              window.open(res?.data);
              hide();
            }
          },
        );
      }}
    >
      <DownloadOutlined />
    </div>,
  ];

  let saveData = (values) => {
    let { dispatch } = props;
    values = {
      ...values,
      service_start_time: values.service[0] || '',
      service_end_time: values.service[1] || '',
      other_business_id: query.other_business_id
        ? query.other_business_id
        : iftype?.curitem?.other_business_id
        ? iftype?.curitem?.other_business_id
        : null,
    };
    if (iftype.val == 'add') {
      dispatch({
        type: 'business/addpaymentorder',
        payload: values,
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    } else if (iftype.val == 'edit') {
      dispatch({
        type:
          iftype.type == 'cashier_refuse'
            ? 'business/cashierretry'
            : iftype.type == 'cache'
            ? 'business/paymentordercash'
            : 'business/addpaymentorder',
        payload: { ...values, id: iftype.id },
      }).then((res) => {
        if (res.code == 0) {
          message.success('操作成功');
          reload();
          cvs(false);
        }
      });
    }
  };

  useEffect(() => {
    if (query.id) {
      setTimeout(() => {
        cvs(true);
      }, 100);

      cf((fields) => {
        for (let i in fields) {
          fields[i].value = i == 'service_type' ? 'account' : null;
          if (i == 'company_id') {
            fields[i].value = parseInt(query.id);
          }

          if (query.service_id) {
            fields['service_type'].value = 'other';
            fields['service_id'].value = parseInt(query.service_id);
          }
          if (query.receivable) {
            fields['receivable'].value = query.receivable;
          }
          if (query.service) {
            fields['service'].value = query.service;
          }
        }
        return { ...fields };
      });
      ciftype({
        val: 'add',
        title: '新增收款单',
      });
    }
  }, [query]);

  return (
    <div className="pgcontainer">
      <AutoTable
        pagetitle={props.route.name} //页面标题
        pageextra={extrarender} //页面操作 新增or批量删除
        columns={columns}
        actionRef={actionRef}
        formRef={formRef}
        onRef={(node) => (ChildRef = node)}
        path="/wbn-api/payment_order"
        extraparams={{ type: 0 }}
        //withCard={false}
        //cardtitle = "name" //卡片标题
        //cardavatar = "img_url" //卡片头像
      ></AutoTable>
      <Modal
        maskClosable={false}
        title={iftype.title}
        open={vs}
        onCancel={() => cvs(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        {iftype.val == 'see' && iftype.curitem ? (
          <ProDescriptions
            title={`收款单的详细信息`}
            columns={[...columns]}
            column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
            dataSource={iftype.curitem}
          />
        ) : (
          <InitForm
            fields={fields}
            submitData={(values) => {
              saveData(values);
            }}
            onChange={(changedValues, allValues) => {
              //联动操作
            }}
            submitting={
              props.loading.effects['business/cashierretry'] ||
              props.loading.effects['business/addpaymentorder'] ||
              !vs
            }
            halfsave={false}
          ></InitForm>
        )}
      </Modal>

      <Modal
        maskClosable={false}
        title={iftype.title}
        visible={vis}
        onCancel={() => cvis(false)}
        footer={false}
        width={1400}
        destroyOnClose={true}
      >
        <ProDescriptions
          title={`${iftype?.curitem?.name}的详细信息`}
          columns={[...columnes]}
          column={{ xs: 1, sm: 1, md: 2, lg: 3, xl: 4, xxl: 5 }}
          dataSource={iftype?.curitem}
        />
      </Modal>
    </div>
  );
}

export default connect(({ business, loading, user }) => ({
  business,
  loading,
  user,
}))(Receipt);
